<template>
  <div class="pay-order-container">
    <div class="address-container-no" @click="changeAddress" v-if="!address">
      <div class="left-container">
        <span class="iconfont icondizhi"></span>
      </div>
      <div class="middle-container">请点击添加地址</div>
      <div class="right-container">
        <span class="iconfont icongengduo"></span>
      </div>
    </div>
    <div class="address-container" @click="changeAddress" v-else>
      <div class="left-container">
        <div class="icon-container">
          <span class="iconfont icondizhi"></span>
        </div>
        <div class="main-container">
          <div class="name">
            <div class="label">收货人：</div>
            <div class="name">{{ address.username }}</div>
          </div>
          <div class="address">{{ address.address }}</div>
        </div>
      </div>
      <div class="middle-container">
        <div class="phone">{{ address.telephone }}</div>
        <div class="tip">默认</div>
      </div>
      <div class="right-container">
        <span class="iconfont icongengduo"></span>
      </div>
    </div>
    <div class="info-container">
      <div class="info-item" v-for="(item, index) in goods" :key="index">
        <div class="left-container">
          <img :src="item.picture" alt />
        </div>
        <div class="right-container">
          <div class="price">{{ type === 'integral' ? '积分：' : '$' }} {{ item.price }}</div>
          <div class="name">{{ item.name }}</div>
          <div class="order-num">x {{ item.num }}
            <span class="specnames">{{ item.specnames }}</span>
          </div>
        </div>
      </div>
    </div>
    <!-- 优惠券 -->
    <div class="coupon-container" v-if="isShow">
      <!-- 优惠券单元格 -->
      <van-coupon-cell :coupons="coupons" :chosen-coupon="chosenCoupon" @click="showList = true" />
    </div>
    <div class="pay-container" v-if="type !== 'integral'">
      <div
        class="pay-item"
        v-for="(item, index) in payType"
        :key="index"
        @click="payIndex = item.index"
      >
        <div class="icon">
          <img :src="item.icon" alt />
        </div>
        <div class="name">{{ item.name }}</div>
        <div class="check">
          <img src="~@/assets/icon/checked.png" alt v-if="payIndex === item.index" />
          <img src="~@/assets/icon/no_checked.png" alt v-else />
        </div>
      </div>
    </div>
    <div class="ok-btn" @click="ok" v-if="type !== 'integral'">
      确认支付：
      <span class="price">$ {{ (totalPrice - couponPrice).toFixed(2) }}</span>
    </div>
    <div class="ok-btn" @click="okIntegral" v-else>
      确认兑换：
      <span class="price">积分 {{ Number(totalPrice).toFixed(2) }}</span>
    </div>
    <!-- 优惠券列表 -->
    <van-popup
      v-model="showList"
      round
      position="bottom"
      :show-exchange-bar="false"
      style="height: 90%; padding-top: 4px;">
      <van-coupon-list
        :coupons="coupons"
        :chosen-coupon="chosenCoupon"
        :disabled-coupons="disabledCoupons"
        @change="onChange"
      />
    </van-popup>
  </div>
</template>

<script>
import pay1 from "@/assets/icon/pay_1.png";
import pay2 from "@/assets/icon/pay_2.png";
import pay3 from "@/assets/icon/pay_3.png";
import { Cache } from "@utils";

export default {
  data() {
    return {
      chosenCoupon: -1,
      showList: false,
      coupons: [],
      disabledCoupons: [],
      address: null,
      goods: [],
      payType: [
        {
          icon: pay1,
          name: "微信支付",
          index: 1
        },
        {
          icon: pay2,
          name: "银联支付",
          index: 2
        },
        {
          icon: pay3,
          name: "货到付款",
          index: 3
        }
      ],
      payIndex: 1,
      couponPrice: 0
    };
  },
  computed: {
    type () {
      return this.$route.query.isType
    },
    isShow () {
      return !['actview', 'figview', 'integral'].includes(this.$route.query.isType)
    },
    totalPrice() {
      let price = 0;
      this.goods.forEach(item => {
        price += item.num * item.price;
      });
      return price.toFixed(2);
    }
  },
  created() {
    this.getShoppingDetsils();
    this.getdAddressList();
    this.getCouponList()
  },
  methods: {
    onChange(index) {
      this.showList = false;
      this.chosenCoupon = index
      if (index === -1) {
        this.couponPrice = 0
      } else {
        this.couponPrice = this.coupons[index].value / 100
      }
    },
    async getCouponList () {
      const result = await this.$fetchGet('/home/member/coupon', {
        type: 1
      })
      if (!result.success) {
        this.$toast(result.msg)
        return
      }
      result.data.list.forEach(item => {
        if (parseFloat(item.cost).toFixed(2) <= this.totalPrice) {
          this.coupons.push({
            id: item.id,
            name: item.title,
            condition: `满${item.cost}减${item.amount}`,
            startAt: item.timefrom,
            endAt: item.timeto,
            unitDesc: '元',
            value: item.amount * 100,
            valueDesc: item.amount,
            no: item.no
          })
        } else {
          this.disabledCoupons.push({
            id: item.id,
            name: item.title,
            condition: `满${item.cost}减${item.amount}`,
            startAt: item.timefrom,
            endAt: item.timeto,
            unitDesc: '元',
            value: item.amount * 100,
            valueDesc: item.amount,
            reason: `消费金额不够${item.cost}元`
          })
        }
      })
    },
    // 获取商品数据
    getShoppingDetsils() {
      this.goods = Cache.get("buyShoppingData");
    },
    async getdAddressList() {
      const res = await this.$fetchGet("/home/member/address");
      if (!res.success) {
        this.$toast(res.msg);
        return;
      }
      if (!res.data.list.length) return;

      const arr = res.data.list.filter(item => item.isdefault);
      this.address = arr.length ? arr[0] : res.data.list[0];
    },
    async ok() {
      let self = this;
      if (!this.address) {
        this.$toast("请先选择地址");
        return;
      }
      if (this.payIndex !== 1) {
        this.$toast("选择支付方式开发中");
        return;
      }
      const type = this.$route.query.type;
      let url;
      let params = {
        addressid: this.address.id,
        paymethod: 1,
        remark: null
      };
      if (this.chosenCoupon !== -1) {
        params.couponno = this.coupons[this.chosenCoupon].no
      }
      if (type === "cart") {
        // 购物车订单提交
        url = "/home/settle/confirm";
      } else if (type === "good") {
        // 直接购买
        url = "/home/settle/direct";
        params.productid = this.goods[0].id;
        params.num = this.goods[0].num;
        params.specification = this.goods[0].specification;
      } else if (type === "figview") {
        // 发起拼团
        url = "/home/settle/direct";
        params.productid = this.goods[0].id;
        params.num = this.goods[0].num;
        params.people = this.goods[0].people;
        params.specification = this.goods[0].specification;
      } else if (type === 'figviewJoin') {
        // 参与拼团
        url = '/home/settle/pin'
        params.productid = this.goods[0].id;
        params.num = this.goods[0].num;
        params.people = this.goods[0].people;
        params.group_id = this.goods[0].figviewId
        params.specification = this.goods[0].specification
      }
      const res = await this.$fetchPost(url, params);
      if (!res.success) {
        this.$toast(res.msg);
        return;
      }
      if (type === "cart") {
        this.$store.commit("changeCartList");
      }

      if (this.payIndex === 1) {
        // 微信支付
        const res1 = await this.$fetchGet("/home/pay/wxpay", {
          orderno: res.data.orderno
        });
        if (res1.success) {
          window.location.href = res1.data.url;
        } else {
          this.$toast(res1.msg);
        }
      }
    },
    // 积分兑换
    async okIntegral () {
      let self = this;
      if (!this.address) {
        this.$toast("请先选择地址");
        return;
      }
      const result = await this.$fetchPost('/home/settle/direct', {
        productid: this.goods[0].id,
        num: this.goods[0].num,
        addressid: this.address.id,
        remark: '积分兑换',
        balance2: Number(this.totalPrice)
      })
      if (!result.success) {
        this.$toast(result.msg)
        return
      }
      this.$router.push('/my')
    },
    changeAddress() {
      this.$router.push({
        path: "/address",
        query: {
          type: "select"
        }
      });
      console.log(123);
    }
  }
};
</script>

<style lang="scss">
.pay-order-container {
  .address-container-no {
    margin-top: 50px;
    box-shadow: 0 0 10px #888;
    background: #ffffff;
    padding: 30px;
    display: flex;
    font-size: 30px;
    line-height: 80px;
    .left-container {
      color: #f00;
    }
    .middle-container {
      margin-left: 50px;
      flex: 1;
    }
  }
  .address-container {
    margin-top: 50px;
    box-shadow: 0 0 10px #888;
    background: #ffffff;
    padding: 30px;
    display: flex;
    font-size: 25px;
    .left-container {
      display: flex;
      flex: 1;
      .icon-container {
        line-height: 80px;
        color: #f00;
        .iconfont {
          font-size: 40px;
        }
      }
      .main-container {
        font-size: 30px;
        margin-left: 20px;
        .name {
          display: flex;
          margin-bottom: 10px;
          .label {
            color: #888;
          }
        }
      }
    }
    .middle-container {
      text-align: right;
      font-size: 30px;
      .tip {
        padding: 5px 10px;
        background: #f00;
        color: #fff;
        display: inline-block;
        margin-top: 10px;
      }
    }
    .right-container {
      margin-left: 20px;
      line-height: 80px;
      .iconfont {
        font-size: 30px;
      }
    }
  }
  .info-container {
    margin-top: 50px;
    box-shadow: 0 0 10px #888;
    background: #ffffff;
    padding: 30px;
    .info-item {
      display: flex;
      &:not(:first-child) {
        margin-top: 30px;
      }
    }
    .left-container {
      width: 150px;
      height: 150px;
    }
    .right-container {
      flex: 1;
      margin-left: 50px;
      .price {
        font-size: 30px;
        color: #ff3b3b;
        font-weight: bold;
      }
      .name {
        font-size: 30px;
        margin-top: 20px;
        color: #646464;
      }
      .order-num {
        margin-top: 10px;
        font-size: 30px;
        color: #646464;
        .specnames {
          font-size: 25px;
        }
      }
    }
  }
  .coupon-container {
    margin-top: 50px;
    box-shadow: 0 0 10px #888;
    background: #ffffff;
    padding: 30px;
    display: flex;
    font-size: 25px;
  }
  .pay-container {
    margin-top: 50px;
    box-shadow: 0 0 10px #888;
    background: #ffffff;
    padding: 0 30px;
    .pay-item {
      display: flex;
      border-bottom: 1px solid #e5e5e5;
      padding: 20px 0;
      cursor: pointer;
      .icon {
        width: 50px;
        height: 50px;
      }
      .name {
        flex: 1;
        margin-left: 30px;
        line-height: 50px;
      }
      .check {
        img {
          width: 50px;
          height: 50px;
        }
      }
    }
  }
  .ok-btn {
    margin-top: 50px;
    width: 80vw;
    font-size: 30px;
    margin-left: 10vw;
    text-align: center;
    line-height: 100px;
    background: linear-gradient(to right, #fc8f04, #f71c19);
    border-radius: 50px;
    color: #fff;
    .price {
      // font-size: 35px;
      font-weight: bold;
    }
  }
}
</style>